package com.djl.homework;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author djl
 * @Time 2024/9/29 19:14
 */
public class Ex2 {
    private int booksNum = 10;
    private int books = 10;
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private  Condition condition2 = lock.newCondition();
    public synchronized void method1() throws InterruptedException {
        lock.lock();
        try {
            while (booksNum <= 0) {
                condition1.await(); // 注意这里使用的是while循环
            }
            System.out.println("读者a请求借书");
            booksNum --;
            System.out.println("读者a借到一本，剩余" + booksNum + "本");
        } finally {
            lock.unlock();
        }

    }
    public synchronized  void method2() throws InterruptedException {
        lock.lock();
        try {
            while (booksNum <= 0) {
                condition2.await(); // 注意这里使用的是while循环
            }
            System.out.println("读者b请求借书");
            booksNum --;
            System.out.println("读者b借到一本，剩余" + booksNum + "本");
        } finally {
            lock.unlock();
        }
    }
    public synchronized void method3() throws InterruptedException {
        lock.lock(); // 添加这一行来获取锁
        try {
            if(booksNum > 0){
                condition1.signal();
                condition2.signal();
            }
            if(booksNum < books){
                Thread.sleep(1000);
                booksNum ++ ;
                System.out.println("管理员归还一本已借图书，还有" + booksNum + "本书");
            }
        } finally {
            lock.unlock(); // 添加这一行来释放锁
        }
    }

    public static void main(String[] args) {
        Ex2 ex2 = new Ex2();
        new Thread(()->{
            try {
                ex2.method1();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        new Thread(()->{
            try {
                ex2.method2();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        new Thread(()->{
            try {
                ex2.method3();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
}
